import defaultSettings from "@/settings";
import { useDynamicTitle } from "@/utils/dynamicTitle";

const {
  sideTheme,
  showSettings,
  topNav,
  tagsView,
  fixedHeader,
  sidebarLogo,
  dynamicTitle,
} = defaultSettings;

// 修复localStorage可能为null的情况
const storageSetting = JSON.parse(
  localStorage.getItem("layout-setting") || "{}"
);

const useSettingsStore = defineStore("settings", {
  state: () => ({
    title: "",
    theme: storageSetting.theme || "#1976D2", // 改为Quasar默认主题色
    sideTheme: storageSetting.sideTheme || sideTheme,
    showSettings: showSettings,
    topNav:
      storageSetting.topNav === undefined ? topNav : storageSetting.topNav,
    tagsView:
      storageSetting.tagsView === undefined
        ? tagsView
        : storageSetting.tagsView,
    fixedHeader:
      storageSetting.fixedHeader === undefined
        ? fixedHeader
        : storageSetting.fixedHeader,
    sidebarLogo:
      storageSetting.sidebarLogo === undefined
        ? sidebarLogo
        : storageSetting.sidebarLogo,
    dynamicTitle:
      storageSetting.dynamicTitle === undefined
        ? dynamicTitle
        : storageSetting.dynamicTitle,
  }),
  actions: {
    // 修改布局设置
    changeSetting(data) {
      const { key, value } = data;
      if (Object.prototype.hasOwnProperty.call(this, key)) {
        // 修复了Object.hasOwnProperty的调用方式
        this[key] = value;
        // 保存设置到localStorage
        const setting = {
          theme: this.theme,
          sideTheme: this.sideTheme,
          topNav: this.topNav,
          tagsView: this.tagsView,
          fixedHeader: this.fixedHeader,
          sidebarLogo: this.sidebarLogo,
          dynamicTitle: this.dynamicTitle,
        };
        localStorage.setItem("layout-setting", JSON.stringify(setting));
      }
    },
    // 设置网页标题
    setTitle(title) {
      this.title = title;
      useDynamicTitle();
    },
    // 重置为默认设置
    resetSettings() {
      this.theme = "#1976D2";
      this.sideTheme = sideTheme;
      this.topNav = topNav;
      this.tagsView = tagsView;
      this.fixedHeader = fixedHeader;
      this.sidebarLogo = sidebarLogo;
      this.dynamicTitle = dynamicTitle;
      localStorage.removeItem("layout-setting");
    },
  },
});

export default useSettingsStore;
